import { FC, useState, useEffect, useRef, useCallback, memo } from "react"
import { View, ViewStyle, TextStyle } from "react-native"

import { Text } from "@/components/Text"
import { sendStreamingChatCompletion } from "@/services/api/openaiHK"
import type { ChatMessage } from "@/services/api/types"
import { useAppTheme } from "@/theme/context"
import type { ThemedStyle } from "@/theme/types"

interface SSEMessageProps {
  id: string
  request: {
    model: string
    messages: ChatMessage[]
    max_tokens: number
    temperature: number
    top_p: number
    presence_penalty: number
  }
  onComplete?: (completeMessage: string) => void
  onError?: (error: Error) => void
  style?: {
    container?: ThemedStyle<ViewStyle>
    bubble?: ThemedStyle<ViewStyle>
    text?: ThemedStyle<TextStyle>
    time?: ThemedStyle<TextStyle>
  }
}

interface MessageState {
  content: string
  timestamp: Date
  isStreaming: boolean
  isComplete: boolean
  error?: string
}

/**
 * SSE消息组件 - 专门处理流式响应的独立组件
 * 使用memo优化，避免父组件重渲染时的不必要更新
 */
export const SSEMessage: FC<SSEMessageProps> = memo(
  ({ id, request, onComplete, onError, style }) => {
    const { themed } = useAppTheme()
    const [messageState, setMessageState] = useState<MessageState>({
      content: "",
      timestamp: new Date(),
      isStreaming: false,
      isComplete: false,
    })

    const sseClientRef = useRef<any>(null)
    const timeoutRef = useRef<NodeJS.Timeout | any>(null)
    const onCompleteRef = useRef(onComplete)
    const onErrorRef = useRef(onError)
    const messageRole: "user" | "assistant" = "assistant"

    // 更新refs
    onCompleteRef.current = onComplete
    onErrorRef.current = onError

    // 清理SSE连接
    const cleanupSSEConnection = useCallback(() => {
      if (sseClientRef.current) {
        sseClientRef.current.disconnect()
        sseClientRef.current = null
      }
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current)
        timeoutRef.current = null
      }
    }, [])

    // 开始流式响应
    const startStreaming = useCallback(() => {
      console.log(`Starting streaming for message ${id}`)

      setMessageState((prev) => ({ ...prev, isStreaming: true, error: undefined }))

      // 设置超时处理
      timeoutRef.current = setTimeout(() => {
        console.error(`Streaming timeout for message ${id}`)
        setMessageState((prev) => ({
          ...prev,
          isStreaming: false,
          isComplete: true,
          error: "请求超时，请重试",
        }))
        cleanupSSEConnection()
        onError?.(new Error("Streaming timeout"))
      }, 30000) // 30秒超时

      try {
        sseClientRef.current = sendStreamingChatCompletion(request, {
          onOpen: () => {
            console.log(`SSE connection opened for message ${id}`)
          },
          onMessage: (content: string) => {
            console.log(`Received content for message ${id}:`, content)
            setMessageState((prev) => ({
              ...prev,
              content: prev.content + content,
            }))
          },
          onComplete: () => {
            console.log(`SSE stream completed for message ${id}`)
            if (timeoutRef.current) {
              clearTimeout(timeoutRef.current)
              timeoutRef.current = null
            }
            setMessageState((prev) => ({
              ...prev,
              isStreaming: false,
              isComplete: true,
            }))
            console.log("检查父组件", sseClientRef.current)
            // 通知父组件完成
            if (sseClientRef.current) {
              const completeMessage = sseClientRef.current.getCompleteMessage()
              console.log(`Complete message for ${id}:`, completeMessage)
              onCompleteRef.current?.(completeMessage)
            }
            cleanupSSEConnection()
          },
          onError: (error: Error) => {
            console.error(`SSE error for message ${id}:`, error)
            if (timeoutRef.current) {
              clearTimeout(timeoutRef.current)
              timeoutRef.current = null
            }
            setMessageState((prev) => ({
              ...prev,
              isStreaming: false,
              isComplete: true,
              error: error.message,
            }))
            cleanupSSEConnection()
            onErrorRef.current?.(error)
          },
        })
      } catch (error) {
        console.error(`Failed to start streaming for message ${id}:`, error)
        if (timeoutRef.current) {
          clearTimeout(timeoutRef.current)
          timeoutRef.current = null
        }
        setMessageState((prev) => ({
          ...prev,
          isStreaming: false,
          isComplete: true,
          error: (error as Error).message,
        }))
        onErrorRef.current?.(error as Error)
      }
    }, [request, id, cleanupSSEConnection])

    // 组件挂载时开始流式响应
    useEffect(() => {
      console.log(`SSEMessage mounted for ${id}`)
      startStreaming()

      // 组件卸载时清理连接
      return () => {
        console.log(`SSEMessage unmounting for ${id}`)
        cleanupSSEConnection()
      }
    }, []) // 移除依赖，避免重复执行

    // 渲染消息内容
    const renderContent = () => {
      if (messageState.error) {
        return (
          <Text style={themed(style?.text || $defaultMessageText(messageRole))}>
            抱歉，连接出现问题，请重试。
          </Text>
        )
      }

      if (!messageState.content && messageState.isStreaming) {
        return <Text style={themed(style?.text || $defaultMessageText(messageRole))}>...</Text>
      }

      return (
        <Text style={themed(style?.text || $defaultMessageText(messageRole))}>
          {messageState.content}
        </Text>
      )
    }

    return (
      <View style={themed(style?.container || $defaultMessageContainer(messageRole))}>
        <View style={themed(style?.bubble || $defaultMessageBubble(messageRole))}>
          {renderContent()}
        </View>
        <Text style={themed(style?.time || $defaultMessageTime)}>
          {messageState.timestamp.toLocaleTimeString()}
        </Text>
      </View>
    )
  },
)

// 设置displayName用于调试
SSEMessage.displayName = "SSEMessage"

// 默认样式
const $defaultMessageContainer =
  (role: "user" | "assistant"): ThemedStyle<ViewStyle> =>
  ({ spacing }) => ({
    marginBottom: spacing.sm,
    alignItems: role === "user" ? "flex-end" : "flex-start",
  })

const $defaultMessageBubble =
  (role: "user" | "assistant"): ThemedStyle<ViewStyle> =>
  ({ colors, spacing }) => ({
    maxWidth: "80%",
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    borderRadius: 16,
    backgroundColor: role === "user" ? colors.palette.neutral300 : colors.palette.neutral200,
    borderBottomRightRadius: role === "user" ? 4 : 16,
    borderBottomLeftRadius: role === "user" ? 16 : 4,
  })

const $defaultMessageText =
  (role: "user" | "assistant"): ThemedStyle<TextStyle> =>
  ({ colors }) => ({
    color: colors.text,
    fontSize: 16,
    lineHeight: 20,
  })

const $defaultMessageTime: ThemedStyle<TextStyle> = ({ colors, spacing }) => ({
  color: colors.textDim,
  fontSize: 12,
  marginTop: spacing.xs,
  textAlign: "center",
})

// 导出类型
export type { SSEMessageProps, MessageState }
